package org.qs.webservice.sign;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.digest.DigestUtils;

public class MD5 {
	  public static String getMD5(String plaintext)
	  {
	    try
	    {
	      MessageDigest md = MessageDigest.getInstance("MD5");

	      md.reset();
	      md.update(plaintext.getBytes());
	      byte[] digest = md.digest();
	      BigInteger bigInt = new BigInteger(1, digest);
	      String hashtext;
	      for ( hashtext = bigInt.toString(16); hashtext.length() < 32; hashtext = "0" + hashtext);
	      return hashtext;
	    }
	    catch (NoSuchAlgorithmException e1)
	    {
	    	e1.printStackTrace();
	    }
	    return "";
	  }
	  public static String sign(String text, String key, String input_charset)
	  {
	    text = text + key;
	    return DigestUtils.md5Hex(getContentBytes(text, input_charset));
	  }

	  public static boolean verify(String text, String sign, String key, String input_charset)
	  {
	    text = text + key;
	    String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
	    if (mysign.equals(sign)) {
	      return true;
	    }

	    return false;
	  }

	  private static byte[] getContentBytes(String content, String charset)
	  {
	    if ((charset == null) || ("".equals(charset)))
	      return content.getBytes();
	    try
	    {
	      return content.getBytes(charset); } catch (UnsupportedEncodingException e) {
	    }
	    throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
	  }
	}